package itheima02;

import org.junit.Test;
import utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
    使用JDBC工具类完成增删改

    增,改,自己完成

    步骤:

        1.使用JDBC工具类获取连接Connection对象
        2.获取执行SQL语句的Statement对象
        3.Statement对象执行sql语句
        4.关闭资源
 */
public class Demo02JDBCUtil {
    //删除一条记录: 添加异常处理的代码
    @Test
    public void deleteOne() {
        //提示变量的作用域
        Connection con = null;
        Statement stmt = null;
        try{
            //1.使用JDBC工具类获取连接Connection对象
            con = JDBCUtil.getConnection();

            //2.获取执行SQL语句的Statement对象
            stmt = con.createStatement();

            //定义sql语句
            String sql = "delete from scores where sid=1";

            //3.Statement对象执行sql语句
            int result = stmt.executeUpdate(sql);
            if(result>0) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if(con!=null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stmt!=null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

/*
public class Demo02JDBCUtil {
    @Test
    public  void  test(){
       Connection connection=null;
       Statement statement=null;
        ResultSet resultSet=null;
       try{
          connection=JDBCUtil.getConnection();
          statement=connection.createStatement();

          String sql="select * from scores";
          resultSet=statement.executeQuery(sql);
          while (resultSet.next()){
              Object sid=resultSet.getObject(1);
              Object score=resultSet.getObject(2);
              Object sname=resultSet.getObject(3);
              System.out.println("编号: "+sid+", 姓名: "+sname+", 成绩: "+score);
          }
       } catch (SQLException e) {
           e.printStackTrace();
       } finally {
           JDBCUtil.release(connection,statement,resultSet);
       }
    }
}*/
